import { Page, expect, BrowserContext, TestInfo } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';

export class TestHelpers {
  /**
   * 用户登录
   */
  static async login(
    page: Page,
    username: string = process.env.TEST_USERNAME || 'testuser',
    password: string = process.env.TEST_PASSWORD || 'password123'
  ): Promise<void> {
    console.log(`🔐 用户登录: ${username}`);

    // 等待登录按钮出现
    const loginButton = page.locator('[data-testid="login-button"], [data-cy="login-button"]');
    await loginButton.waitFor({ state: 'visible', timeout: 10000 });
    await loginButton.click();

    // 填写登录表单
    const usernameInput = page.locator('[data-testid="username-input"], [data-cy="username-input"]');
    const passwordInput = page.locator('[data-testid="password-input"], [data-cy="password-input"]');
    const submitButton = page.locator('[data-testid="submit-login"], [data-cy="submit-login"]');

    await usernameInput.fill(username);
    await passwordInput.fill(password);
    await submitButton.click();

    // 验证登录成功
    const userMenu = page.locator('[data-testid="user-menu"], [data-cy="user-menu"]');
    await userMenu.waitFor({ state: 'visible', timeout: 10000 });

    console.log('✅ 登录成功');
  }

  /**
   * 用户登出
   */
  static async logout(page: Page): Promise<void> {
    console.log('🚪 用户登出');

    // 点击用户菜单
    const userMenu = page.locator('[data-testid="user-menu"], [data-cy="user-menu"]');
    await userMenu.click();

    // 点击登出按钮
    const logoutButton = page.locator('[data-testid="logout-button"], [data-cy="logout-button"]');
    await logoutButton.click();

    // 验证登出成功
    const loginButton = page.locator('[data-testid="login-button"], [data-cy="login-button"]');
    await loginButton.waitFor({ state: 'visible', timeout: 10000 });

    console.log('✅ 登出成功');
  }

  /**
   * 导航到指定页面
   */
  static async navigateTo(page: Page, path: string): Promise<void> {
    console.log(`🧭 导航到: ${path}`);

    // 尝试点击导航菜单
    const navLink = page.locator(`[data-testid="nav-${path}"], [data-cy="nav-${path}"]`);

    try {
      await navLink.waitFor({ state: 'visible', timeout: 5000 });
      await navLink.click();
    } catch (error) {
      // 如果导航菜单不可用，直接使用URL导航
      await page.goto(`/${path}`);
    }

    // 验证导航成功
    await expect(page).toHaveURL(new RegExp(`/${path}$`));
    console.log(`✅ 导航成功: ${path}`);
  }

  /**
   * 等待API调用完成
   */
  static async waitForApiCall(page: Page, urlPattern: string, timeout: number = 10000): Promise<void> {
    console.log(`⏳ 等待API调用: ${urlPattern}`);

    await page.waitForResponse(response =>
      response.url().includes(urlPattern) && response.status() === 200,
      { timeout }
    );

    console.log('✅ API调用完成');
  }

  /**
   * 拍摄截图
   */
  static async takeScreenshot(page: Page, name: string, testInfo?: TestInfo): Promise<void> {
    if (process.env.TAKE_SCREENSHOTS_ON_FAILURE !== 'false') {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      let screenshotName = `${name}_${timestamp}`;

      if (testInfo) {
        screenshotName = `${testInfo.titlePath.join('_')}_${screenshotName}`;
      }

      const screenshotPath = path.join(process.cwd(), 'screenshots', `${screenshotName}.png`);

      // 确保截图目录存在
      const screenshotsDir = path.dirname(screenshotPath);
      if (!fs.existsSync(screenshotsDir)) {
        fs.mkdirSync(screenshotsDir, { recursive: true });
      }

      await page.screenshot({
        path: screenshotPath,
        fullPage: true,
        animations: 'disabled'
      });

      console.log(`📸 截图已保存: ${screenshotPath}`);
    }
  }

  /**
   * 等待加载完成
   */
  static async waitForLoadingComplete(page: Page): Promise<void> {
    console.log('⏳ 等待页面加载完成...');

    // 等待加载指示器消失
    const loadingIndicator = page.locator('[data-testid="loading"], [data-cy="loading"], .ant-spin, .loading');

    try {
      await loadingIndicator.waitFor({ state: 'hidden', timeout: 15000 });
    } catch (error) {
      console.log('⚠️  加载指示器检查超时，继续执行');
    }

    // 等待网络空闲
    await page.waitForLoadState('networkidle', { timeout: 10000 });
    console.log('✅ 页面加载完成');
  }

  /**
   * 创建测试Agent
   */
  static async createTestAgent(
    page: Page,
    agentData: {
      name?: string;
      description?: string;
      model?: string;
      capabilities?: string[];
    } = {}
  ): Promise<void> {
    console.log('🤖 创建测试Agent');

    const defaultData = {
      name: process.env.TEST_AGENT_NAME || '测试Agent',
      description: process.env.TEST_AGENT_DESCRIPTION || '用于自动化测试的AI Agent',
      model: process.env.TEST_MODEL || 'gpt-4',
      capabilities: ['对话', '代码生成', '文档生成']
    };

    const data = { ...defaultData, ...agentData };

    // 点击创建Agent按钮
    const createButton = page.locator('[data-testid="create-agent"], [data-cy="create-agent"]');
    await createButton.waitFor({ state: 'visible', timeout: 10000 });
    await createButton.click();

    // 填写Agent信息
    const nameInput = page.locator('[data-testid="agent-name"], [data-cy="agent-name"]');
    const descriptionInput = page.locator('[data-testid="agent-description"], [data-cy="agent-description"]');
    const modelSelect = page.locator('[data-testid="agent-model"], [data-cy="agent-model"]');

    await nameInput.fill(data.name);
    await descriptionInput.fill(data.description);
    await modelSelect.selectOption({ label: data.model });

    // 保存Agent
    const saveButton = page.locator('[data-testid="save-agent"], [data-cy="save-agent"]');
    await saveButton.click();

    // 验证创建成功
    await expect(page.locator(`text=${data.name}`)).toBeVisible({ timeout: 10000 });
    console.log(`✅ Agent创建成功: ${data.name}`);
  }

  /**
   * 等待Toast消息
   */
  static async waitForToast(page: Page, message: string, type: 'success' | 'error' | 'warning' = 'success'): Promise<void> {
    console.log(`📨 等待Toast消息: ${message}`);

    const toastSelector = `.ant-message-${type} .ant-message-content`;
    await expect(page.locator(toastSelector)).toContainText(message, { timeout: 5000 });
    console.log('✅ Toast消息显示成功');
  }

  /**
   * 验证API响应
   */
  static async verifyApiResponse(page: Page, method: string, url: string, expectedStatus: number = 200): Promise<void> {
    console.log(`🔍 验证API响应: ${method} ${url}`);

    const response = await page.request.fetch(url, { method });
    expect(response.status()).toBe(expectedStatus);

    console.log(`✅ API响应验证成功: ${response.status()}`);
  }

  /**
   * 执行性能测试
   */
  static async measurePerformance(page: Page, action: () => Promise<void>, actionName: string): Promise<number> {
    console.log(`⏱️  测量性能: ${actionName}`);

    const startTime = Date.now();
    await action();
    const endTime = Date.now();
    const duration = endTime - startTime;

    console.log(`⏱️  ${actionName} 耗时: ${duration}ms`);

    // 性能断言
    const threshold = parseInt(process.env.TEST_PERFORMANCE_THRESHOLD || '5000');
    expect(duration).toBeLessThan(threshold);

    return duration;
  }

  /**
   * 处理模态框
   */
  static async handleModal(page: Page, action: 'confirm' | 'cancel' = 'confirm'): Promise<void> {
    console.log(`🔄 处理模态框: ${action}`);

    const modalSelector = '.ant-modal';
    await expect(page.locator(modalSelector)).toBeVisible();

    const buttonSelector = action === 'confirm'
      ? '[data-testid="modal-confirm"], [data-cy="modal-confirm"], .ant-modal-confirm-btn .ant-btn-primary'
      : '[data-testid="modal-cancel"], [data-cy="modal-cancel"], .ant-modal-confirm-btn .ant-btn';

    await page.click(buttonSelector);
    console.log(`✅ 模态框处理完成: ${action}`);
  }

  /**
   * 填写表单
   */
  static async fillForm(page: Page, formData: Record<string, string>): Promise<void> {
    console.log('📝 填写表单');

    for (const [field, value] of Object.entries(formData)) {
      const selector = `[data-testid="${field}"], [data-cy="${field}"], [name="${field}"]`;
      const input = page.locator(selector);

      await input.waitFor({ state: 'visible', timeout: 5000 });
      await input.fill(value);
      console.log(`📝 填写字段 ${field}: ${value}`);
    }

    console.log('✅ 表单填写完成');
  }

  /**
   * 获取测试数据
   */
  static getTestData() {
    return {
      user: {
        username: process.env.TEST_USERNAME || 'testuser',
        password: process.env.TEST_PASSWORD || 'password123',
        email: 'test@example.com'
      },
      admin: {
        username: process.env.TEST_ADMIN_USERNAME || 'admin',
        password: process.env.TEST_ADMIN_PASSWORD || 'admin123',
        email: 'admin@example.com'
      },
      agent: {
        name: process.env.TEST_AGENT_NAME || '测试Agent',
        description: process.env.TEST_AGENT_DESCRIPTION || '用于自动化测试的AI Agent',
        model: process.env.TEST_MODEL || 'gpt-4'
      },
      endpoints: {
        api: process.env.REACT_APP_API_URL || 'http://localhost:6001',
        frontend: process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:3001'
      }
    };
  }
}